import typeOf from "../methods/typeOf"
/**
 * 转换金额为中文大写
 * @param number
 */
const formatNumberToChinese = (number) => {
  if(!typeOf(number, 'number')) {
    return number // 非 number 类型不处理
  }

  const cnNums = ["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"] // 汉字的数字
  const basicUnits = ["","拾","佰","仟"] // 基本单位
  const extensionUnits = ["","万","亿","兆"] //对应整数部分扩展单位
  const decUnits = ["角","分","毫","厘"] // 对应小数部分单位
  const lastUnit = '元'

  let IntegerNum; // 金额整数部分
  let DecimalNum; // 金额小数部分
  let chineseStr = ''; // 输出的中文金额字符串

  if(number == 0) {
    chineseStr = cnNums[0] + lastUnit
    return chineseStr
  }
  number = number.toString() // 转换为字符串
  if(number.indexOf(".") == -1) {
    IntegerNum = number;
    DecimalNum = ''
  } else {
    let parts = number.split('.')
    IntegerNum = parts[0]
    DecimalNum = parts[1].substr(0,4) // 只取到分
  }

  // 整型部分处理
  if(parseInt(IntegerNum, 10) > 0) {
    let zeroCount = 0
    let intLen = IntegerNum.length;
    for(let i = 0; i < intLen; i++) {
      let n = IntegerNum.substr(i, 1) // 每次取一位
      let p = intLen - i - 1
      let q = p / 4
      let m = p % 4
      if( n == "0") {
        zeroCount++
      } else {
        if(zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        zeroCount = 0 // 归零
        chineseStr += cnNums[parseInt(n)] + basicUnits[m]
      }

      if(m == 0 && zeroCount < 4) {
        chineseStr += extensionUnits[q]
      }
    }
    chineseStr += lastUnit
  }

  // 小数部分处理
  if(DecimalNum != '') {
    let decLen = DecimalNum.length
    for(let i = 0; i < decLen; i++) {
      let n = DecimalNum.substr(i, 1)
      if(n != '0') {
        chineseStr += cnNums[Number(n)] + decUnits[i]
      }
    }
  }

  return chineseStr

} 
export default formatNumberToChinese;